import kkNumber from 'kkNumber'

let probabilitySection = [] // 概率区间

const checkProbability = (configs) => {
    let totalProbability = 0
    for (let i = 0; i < configs.length; i++) {
        totalProbability += configs[i].probability
    }

    // console.log(totalProbability)

    if (totalProbability != 100) {
        throw new Error('概率总和不为 100%')
    }

}

const allocateSection = (configs) => {
    for (let i = 0; i < configs.length; i++) {
        if (i == 0) {
            probabilitySection[i] = configs[i].probability
        } else {
            probabilitySection[i] = configs[i].probability + probabilitySection[i - 1]
        }
    }
    // console.log(probabilitySection)
}

export default {
    init(config) {
        checkProbability(config)
        allocateSection(config)
    },
    getAwardIndex() {
        if (probabilitySection.length == 0) {
            throw new Error('请先初始化抽奖模块')
        }

        const figure = kkNumber.getRandomFloatNum(0, 100)
        let result = 0

        for (let i = 0; i < probabilitySection.length; i++) {
            const floor = i == 0 ? 0 : probabilitySection[i - 1]
            const upper = probabilitySection[i]

            if (figure >= floor && figure < upper) {
                result = i
            }

        }

        return result
    }
}